package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.exception.BusinessExciption;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("books")
public class BookController {
    @Autowired
    private BookService bookService;

    //quan bu
    @GetMapping
    public Result getAll(){
        List<Book> list = bookService.findAll();
        Result result = new Result(Code.GET_OK, list, "查询成功");
        return result;
    }
    // cha id
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        if(id==1){
            int a = 1/0;
        }else if(id ==2){
            throw new BusinessExciption(Code.BUSINESS_ERR,"抛出了一个异常222");
        }else if(id ==3){
            throw new SystemException(Code.SYSTEM_ERR,"抛出了一个异常333");
        }
        Book book = bookService.findById(id);
        Result result = new Result(Code.GET_OK, book, "查询成功");
        return result;
    }

    //增加
    @PostMapping
    public Result save(@RequestBody Book book){
        boolean flag = bookService.save(book);
        Result result = new Result(
                flag ? Code.SAVE_OK : Code.SAVE_ERR,
                null,
                flag?"添加成功":"添加失败");
        return result;
    }
    //xiu gai
    @PutMapping
    public Result update(@RequestBody Book book){
        boolean flag = bookService.update(book);
        Result result = new Result(
                flag ? Code.UPDATE_OK : Code.UPDATE_ERR,
                null,
                flag ? "修改成功" : "修改失败");
        return result;
    }
    //shan chu
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = bookService.delete(id);
        Result result = new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR,
                null,
                flag?"删除成功":"删除失败");
        return result;
    }
}
